mod lb;
mod ob;

use lb::LBService;
use pingora::{prelude::*, services::listening::Service};
use prometheus::register_int_counter;
use std::{sync::Mutex, time::Duration};

fn main() {
    env_logger::init();

    let opt = Opt::default();
    let mut my_server = Server::new(opt).unwrap();
    my_server.bootstrap();

    let mut upstreams = LoadBalancer::try_from_iter(["127.0.0.1:8080", "127.0.0.1:8081"]).unwrap();

    /* let ob = ob::ObService::new(String::from("127.0.0.1:19991"));
    let backends = Backends::new(ob);
    let mut upstreams = LoadBalancer::from_backends(backends);
    upstreams.update_frequency = Some(Duration::from_secs(1)); */

    let hc: Box<TcpHealthCheck> = TcpHealthCheck::new();
    upstreams.set_health_check(hc);
    upstreams.health_check_frequency = Some(Duration::from_secs(1));

    let background = background_service("health check", upstreams);
    let upstreams = background.task();

    //let mut lb = http_proxy_service(&my_server.configuration, LBService(Arc::new(upstreams)));
    let mut lb = http_proxy_service(
        &my_server.configuration,
        LBService(upstreams, Mutex::new(0)),
    );

    let reg_cnt = register_int_counter!("reg_counter", "Number of requests").unwrap();
    reg_cnt.inc();

    lb.add_tcp("0.0.0.0:6188");

    my_server.add_service(background);
    my_server.add_service(lb);

    let mut prometheus_service = Service::prometheus_http_service();
    prometheus_service.add_tcp("127.0.0.1:6192");
    my_server.add_service(prometheus_service);
    

    println!("running...");
    my_server.run_forever();
}
